﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPF_CoverView_Demo.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            var dataGrid = sender as DataGrid;
            if (dataGrid != null && dataGrid.SelectedItem == null)
            {
                Console.WriteLine($"ExtentHeight: {e.ExtentHeight}, ViewportHeight: {e.ViewportHeight}, VerticalOffset: {e.VerticalOffset}");

                if (e.ViewportHeight < e.ExtentHeight)
                {
                    var scrollViewer = GetScrollViewer(dataGrid);
                    scrollViewer?.ScrollToEnd(); // 滚动到底部
                    Console.WriteLine("Scrolled to the bottom.");
                }
                else
                {
                    Console.WriteLine("User has manually scrolled, not scrolling automatically.");
                }
            }
            else
            {
                Console.WriteLine("DataGrid has a selected item.");
            }
        }

        // 取消选中项的逻辑
        private void CancelSelection_Click(object sender, RoutedEventArgs e)
        {
            var dataGrid = FindVisualChild<DataGrid>(this);
            if (dataGrid != null)
            {
                dataGrid.SelectedItem = null; // 取消选中
                var scrollViewer = GetScrollViewer(dataGrid);
                scrollViewer?.ScrollToEnd(); // 滚动到底部
                Console.WriteLine("Selection canceled, scrolled to the bottom.");
            }
        }

        // 获取 ScrollViewer 的帮助方法
        private ScrollViewer GetScrollViewer(DependencyObject dep)
        {
            if (dep is ScrollViewer) return dep as ScrollViewer;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep); i++)
            {
                var child = VisualTreeHelper.GetChild(dep, i);
                var result = GetScrollViewer(child);
                if (result != null) return result;
            }
            return null;
        }

        // 查找可视子元素的帮助方法
        private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T typedChild)
                {
                    return typedChild;
                }
                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }
            return null;
        }
    }
}
